function getLocationByUniAPI() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: "wgs84",
			success(lRes) {
				resolve({
					longitude: lRes.longitude,
					latitude: lRes.latitude,
				});
			},
			fail() {
				reject("获取定位失败");
			},
		});
	});
}

export function getAddressInfo(latitude, longitude) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://restapi.amap.com/v3/geocode/regeo', //高德地图逆地址解析接口 
			data: {
				location: `${longitude},${latitude}`,
				key: 'YOUR_AMAP_KEY'
			}, //替换为你的高德地图API Key  
			success(res) {
				resolve(res.data);
			},
			fail() {
				reject("逆地址解析失败");
			}
		});
	});
	8
}
// 腾讯地图逆地址解析
export function getTXAddress(latitude, longitude) {
	console.log("latitude", latitude);



	return new Promise((resolve, reject) => {
		let url = `https://apis.map.qq.com/ws/geocoder/v1/`;
		let params = {
			location: `${latitude},${longitude}`,
			key: "3I4BZ-I3IWQ-Q3W5Q-2QBJT-XWMRS-3SFC5"
		};
		uni.request({
			url: url,
			method: "GET",
			data: params,
			success: (res) => {
				console.log("TX", res);
				if (res.data.status === 0) {
					resolve(res.data);
				} else {

				}
			},
			fail: (err) => {
				reject("逆地址解析失败");
			}
		});
	})
}

// 计算两个字符串的相似度
function calculateSimilarity(str1, str2) {
	// 简单的字符串比较，返回匹配的字符数
	let count = 0;
	for (let i = 0; i < Math.min(str1.length, str2.length); i++) {
		if (str1[i] === str2[i]) {
			count++;
		}
	}
	return count / Math.max(str1.length, str2.length);
}

// 高德地图逆地址解析
export function getGDAddress(latitude, longitude, name) {
	return new Promise((resolve, reject) => {
		const apiKey = 'b6ea6a98b157c121eecabdb1ae703f00';
		const url = `https://restapi.amap.com/v3/geocode/regeo`;

		uni.request({
			method: 'GET',
			url: url,
			data: {
				key: apiKey,
				location: `${longitude},${latitude}`,
				output: 'JSON',
				extensions: 'all',
				radius: 50,
				// homeorcorp: 1, // 综合大数据分析将居家相关的 POI 内容优先返回
			},
			success: (res) => {
				if (res.statusCode === 200) {
					let addressComponent = res.data.regeocode.addressComponent;
					let formatted_address = res.data.regeocode.formatted_address;
					let pois = res.data.regeocode.pois;

					// 找到与 `name` 最匹配的 POI
					let bestMatch = null;
					let bestScore = -1;

					// 使用 async/await 模拟异步处理
					const processPois = async () => {
						if (!name) return null;
						for (const poi of pois) {
							const score = calculateSimilarity(poi.name, name);
							if (score > bestScore) {
								bestScore = score;
								bestMatch = poi;
							}
						}
						return bestMatch;
					};

					processPois().then(() => {
						const info = {
							latitude: latitude,
							longitude: longitude,
							city: addressComponent.city,
							address: formatted_address,
							province: addressComponent.province,
							uid: name ? bestMatch.id : pois[0].id,
							area: addressComponent.district,
							town: addressComponent.township,
							name: name ? name : formatted_address,
							tag: name ? bestMatch.type : pois[0].type,
							...addressComponent
						};
						console.log('请求高德地图API成功，处理后数据为:', info);
						resolve(info);
					});
				} else {
					console.error('获取地址信息失败', res.data);
					reject(res.data);
				}
			},
			fail: (r) => {
				console.error('请求高德地图API失败', r);
				reject(r);
			}
		});
	});
}



// 高德地图搜索POI
export function getGDPoi(poi_id) {
	return new Promise((resolve, reject) => {
		const apiKey = 'b6ea6a98b157c121eecabdb1ae703f00';
		const url = 'https://restapi.amap.com/v3/place/detail'
		const poiId = poi_id
		uni.request({
			method: 'GET',
			url: url,
			data: {
				key: apiKey,
				id: poiId
			},
			success: (res) => {
				if (res.statusCode === 200) {
					console.log('获取到的POI信息:', res);
					resolve(res.data);
				} else {
					console.error('获取POI信息失败', res.data);
				}
			},
			fail: (r) => {
				console.error('请求高德地图POI失败', r);
			}
		});
	})

}



// 百度地图逆地址解析
export function getBDAddress(latitude, longitude) {
	return new Promise((resolve, reject) => {
		const url = `https://api.map.baidu.com/reverse_geocoding/v3/`;
		const params = {
			ak: "58EQO2ycnhddcanpiuKmPMNipwgulhKx",
			output: "json",
			coordtype: "gcj02ll", // **重要**：告诉百度我们传入的是国测局坐标
			location: `${latitude},${longitude}`
		};
		uni.request({
			url: url,
			method: "GET",
			data: params,
			success: (res) => {
				if (res.data && res.data.status === 0) {
					resolve(res.data);
				} else {
					reject(res.data.message || "百度逆地址解析失败");
				}
			},
			fail: (err) => {
				reject("百度逆地址解析请求失败");
			}
		});
	});
}